<template>
  <div class="container">
    <!-- <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>企业人员工资</el-breadcrumb-item>
    </el-breadcrumb>-->
    <!-- 顶部 -->
    <!-- <el-row class="topContent">
            <el-col :span="16">
                <div>
                    <span class="titleTop">企业人员工资</span>
                    <el-link type="primary" @click='downLoad("salaryOperate")' class="uploadBtn">点击下载操作说明</el-link>
                </div>
            </el-col>
            <el-col :span="8" class="alignRight">
                <div>
                    <el-button round type="primary" @click="toCreateSalary" class="createSalaryBut" v-show="makeSalaryBtn">
                        制作工资表
                    </el-button>
                </div>
            </el-col>
    </el-row>-->
    <div class="reminder">
      <i class="el-icon-warning"></i
      >如需下载工资代发授权单，请前往工资表详情页面下载
    </div>
    <div class="topSection">
      <el-row class="topBox">
        <el-col :span="14">
          <div class="fl">
            <el-select
              v-model="projectId"
              filterable
              placeholder="暂无关联项目"
              @change="changeProject"
            >
              <el-option
                v-for="(item, index) of projectList"
                :key="index"
                :label="item.name"
                :value="item.code"
              ></el-option>
            </el-select>
          </div>
        </el-col>
        <el-col :span="10" class="alignRight">
          <div>
            <el-link
              type="primary"
              @click="downLoad('csSalaryOperate')"
              class="uploadBtn"
              >点击下载操作说明</el-link
            >
            <el-button
              round
              type="primary"
              @click="toCreateSalary"
              v-show="isShowAdd"
              class="createSalaryBut"
              >制作工资表</el-button
            >
          </div>
        </el-col>
      </el-row>
    </div>
    <div class="mainCon">
      <el-row class="toolbar searchInputWidth" style="padding-bottom: 0">
        <el-form :inline="true" :model="filterField" ref="searchConditions">
          <el-form-item label="创建时间" class="row-padding-bottom">
            <el-date-picker
              v-model="date"
              type="daterange"
              unlink-panels
              :picker-options="pickerOptions"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="发薪年月" class="row-padding-bottom">
            <el-date-picker
              v-model="filterField.yearMonth"
              type="month"
              value-format="yyyy-MM"
              placeholder="选择月"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="工资表状态" class="row-padding-bottom">
            <el-select
              v-model="filterField.status"
              filterable
              placeholder="请选择"
              clearable
            >
              <el-option
                v-for="item in salaryStateOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <!-- <el-button
              type="primary"
              icon="icon iconfont iconchazhao1"
              @click="searchList"
              class="commonBtn"
            ></el-button> -->
            <el-button
              type="primary"
              icon="icon iconfont iconchazhao1"
              @click="searchList"
              class="searchBtn"
            >
              <span>搜索</span>
            </el-button>
          </el-form-item>
        </el-form>
      </el-row>

      <el-table
        :data="salaryList"
        v-loading="loading"
        :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
        highlight-current-row
        stripe
        style="border: 1px solid #dfe6ec"
      >
        <el-table-column
          prop="year,month,batchNo,createTime"
          label="工资表信息"
          width="200px"
        >
          <template slot-scope="scope">
            <p style="olor: rgb(96, 98, 102); font-weight: bold">
              {{ scope.row.year || '--' }}年{{ scope.row.month || '--' }}月第{{
                scope.row.batchNo || '--'
              }}批次工资
            </p>
            <p style="color: #999; font-size: 12px">
              订单号： {{ scope.row.sequenceCode || '--' }}
            </p>
            <p style="color: #999; font-size: 12px">
              创建日期： {{ scope.row.createTime || '--' }}
            </p>
          </template>
        </el-table-column>
        <el-table-column
          prop="shouldPay,bankActPay"
          label="应发/到账工资总额（元）"
          align="center"
        >
          <template slot-scope="scope">
            <p>
              ￥{{ scope.row.shouldPay || '0' }} / ￥{{
                scope.row.bankActPay || '0'
              }}
            </p>
          </template>
        </el-table-column>
        <el-table-column
          prop="shouldPayTotal,bankActPayTotal"
          label="应发/到账总人数"
          align="center"
          :formatter="formatTd"
        >
          <template slot-scope="scope">
            <p>
              {{ scope.row.shouldPayTotal || '0' }} /
              {{ scope.row.bankActPayTotal || '0' }}
            </p>
          </template>
        </el-table-column>
        <el-table-column
          prop="statusDesc"
          label="工资表状态"
          align="center"
          :formatter="formatTd"
        ></el-table-column>
        <el-table-column label="操作" align="left" fixed="right">
          <template slot-scope="scope">
            <div v-if="scope.row.status == 'NO_PAY'">
              <el-link
                type="primary"
                v-show="isShowDetail"
                @click="toSalaryDetail(scope.$index, scope.row)"
                >查看详情</el-link
              >
              <el-link
                type="primary"
                @click="exporTableAjax(scope.$index, scope.row)"
                v-show="isShowExport"
                >导出</el-link
              >
              <el-link
                type="primary"
                @click="toPay(scope.$index, scope.row)"
                v-show="isShowUpdate"
                >支付</el-link
              >
            </div>
            <div v-else-if="scope.row.status == 'CONFIRMED'">
              <el-link
                type="primary"
                @click="handleEdit(scope.$index, scope.row)"
                v-show="isShowUpdate"
                >编辑</el-link
              >
              <el-link
                type="primary"
                @click="deleteSalary(scope.$index, scope.row)"
                v-show="isShowDel"
                >删除</el-link
              >
              <el-link
                type="primary"
                @click="exporTableAjax(scope.$index, scope.row)"
                v-show="isShowExport"
                >导出</el-link
              >
            </div>
            <div v-else>
              <el-link
                type="primary"
                @click="toSalaryDetail(scope.$index, scope.row)"
                v-show="isShowDetail"
                >查看详情</el-link
              >
              <el-link
                type="primary"
                @click="exporTableAjax(scope.$index, scope.row)"
                v-show="isShowExport"
                >导出</el-link
              >
              <el-link
                type="primary"
                @click="toUploadFile(scope.$index, scope.row)"
                v-show="isShowUpdate"
                >上传附件</el-link
              >
              <el-link
                type="primary"
                @click="toPaySalary(scope.$index, scope.row)"
                >线上代发</el-link
              >
            </div>
          </template>
        </el-table-column>
        <!-- 表格数据为空时，页面显示 -->
        <div slot="empty" v-show="isShow">
          <emptyTable emptyText="暂无相关信息"></emptyTable>
        </div>
      </el-table>
      <!-- filterField为搜索条件 -->
      <!-- getTableList为获取子组件的数据 -->
      <Pagination
        ref="pagination"
        @getList="getTableList"
        :filterField="filterField"
        :requestUrl="requestUrl"
      ></Pagination>
      <!-- 上传合同附件 -->
      <el-dialog
        title="附件"
        :visible.sync="uploadContract"
        :modal-append-to-body="false"
        :append-to-body="true"
      >
        <uploadAnnex
          @getFileList="getFileList"
          :limitationFactor="limitationFactor"
          @getFile="getFile"
          :upLoadFile="uploadImg"
        />,
        <div>
          <elementImage
            :upLoadFile="upLoadFile"
            :srcList="srcList"
            :oldSrcList="oldSrcList"
            @changeSrcList="changeSrcList"
          ></elementImage>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button @click.native="cancelUpload" class="cancel"
            >取消</el-button
          >
          <el-button
            type="primary"
            @click.native="saveUpload"
            class="save"
            :loading="canLogin"
            >保存</el-button
          >
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import common from '../../kits/common'

export default {
  name: 'companySalaryBatchList',
  components: {},
  data() {
    return {
      limitationFactor: {
        uploadAnnexUrl: 'api-f/files/upload', //自定义上传文件接口地址
        upLoadFileLength: 10, //自定义上传文件最大数量设置
        fileSize: 5, //自定义上传文件最大设置
        messageFileSizetip: '最多能上传5M以内的附件', //自定义id解决一个页面包含多个上传附件
        messagetip: '仅支持上传jpg、png、jpeg格式文件，图片大小不超过5M', //自定义报错提示语
        formatType: 'typeOne', //自定义上传格式校验类型
        fileId: 'salaryExcel', //自定义id解决一个页面包含多个上传附件
        uploadFormId: 'salaryExcelForm', //自定义id解决一个页面包含多个上传附件
        methodTip: '', //自定义上传文件提示
        uploadBtnType: 'typeTwo', //自定义上传按钮类型
      },
      projectList: [], //项目名称列表
      projectItem: '',
      projectId: '',
      projectName: '',
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now()
        },
      },
      date: [], //日期区间
      salaryStateOptions: [], //工资表状态下拉框
      requestUrl: 'api-su/cs/salary/expand/list',
      //表格数据
      salaryList: [],
      yearQuery: '', //工资表详情id
      //搜索条件
      filterField: {
        projectId: '',
        createTimeStart: '',
        createTimeEnd: '',
        yearMonth: '',
        status: '',
      },
      isShow: false, //列表加载
      loading: true,
      uploadImg: [],
      saveImgArr: [],
      srcList: [],
      oldSrcList: [],
      canLogin: false, //保存loading
      uploadContract: false, //上传合同附件
      salaryId: '', //工资id
      isShowDel: '',
      isShowUpdate: '',
      isShowAdd: '',
      isShowExport: '',
      isShowDetail: '',
    }
  },
  created() {
    this.$store.state.activeMenu = '/home/salaryDf/companySalaryBatchList'

    this.projectName = this.projectName
      ? this.projectName
      : this.$route.query.projectName
    this.getProjectList()
    //工资表状态下拉框
    this.getSalaryState()
    this.isShowAdd =
      this.$store.state.buttonLimitsArr.indexOf('csSalaryList:add') > -1
    this.isShowUpdate =
      this.$store.state.buttonLimitsArr.indexOf('csSalaryList:update') > -1
    this.isShowDel =
      this.$store.state.buttonLimitsArr.indexOf('csSalaryList:delete') > -1
    this.isShowExport =
      this.$store.state.buttonLimitsArr.indexOf('csSalaryList:export') > -1
    this.isShowDetail =
      this.$store.state.buttonLimitsArr.indexOf('csSalaryList:detail') > -1
  },
  methods: {
    /**
     * @description: 获取上传的附件
     */
    getFileList(val) {
      this.oldSrcList.push(val)
      this.srcList.push(val)
    },
    /**
     * @description: 获取上传的附件
     */
    getFile(val) {
      this.upLoadFile = val
    },
    changeProject(val) {
      this.projectId = val
      localStorage.setItem('projectSalary', this.projectId)
      let obj = {}
      obj = this.projectList.find((item) => {
        return item.code === val
      })

      this.projectItem = obj
      this.filterField.projectId = this.projectItem.code
      this.projectName = this.projectItem.name
      this.$nextTick(function () {
        this.$refs.pagination.getTableListData()
      })
    },
    //获取项目列表
    getProjectList() {
      this.axios({
        method: 'post',
        url: 'api-p/projectcompany/expand/current/projects',
      })
        .then(
          (response) => {
            if (!response.data.hasError) {
              this.projectList = response.data.result
              //建筑端企业端项目详情跳转工资表,判断路由是否传项目id与项目名称
              if (response.data.result.length > 0) {
                if (this.$route.query.projectId) {
                  this.projectId = this.$route.query.projectId
                  this.filterField.projectId = this.projectId
                  let obj = {}
                  obj = this.projectList.find((item) => {
                    return item.code === this.projectId
                  })
                  this.projectItem = obj
                  this.projectName = obj.name
                } else {
                  if (localStorage.getItem('projectSalary')) {
                    this.projectId = localStorage.getItem('projectSalary')
                  } else {
                    this.projectId = response.data.result[0].code
                  }
                  this.projectName = response.data.result[0].name
                  this.projectItem = response.data.result[0]
                  localStorage.setItem('projectSalary', this.projectId)
                  this.filterField.projectId = this.projectId
                }
              } else {
                this.$alert('您还未加入项目请前往项目申请页面申报项目', '', {
                  confirmButtonText: '确定',
                  confirmButtonClass: 'messageButColor',
                  showClose: false,
                })
                  .then(() => {
                    this.$router.push({
                      path: '/home/project/projectDeclareList',
                      name: 'projectDeclareList',
                      query: {
                        type: 'projectDeclareList',
                      },
                    })
                    this.$store.commit('CHANGE_SLIDER_NAME', {
                      oldUrl: '/home/project/projectDeclareList',
                      newUrl: this.$router.currentRoute.fullPath,
                    })
                  })
                  .catch(() => {})
              }
              this.$nextTick(function () {
                this.$refs.pagination.getTableListData()
              })
            } else {
              this.$message.error('项目数据获取失败')
            }
          },
          (res) => {
            this.$message.error('项目数据获取失败')
          }
        )
        .catch((error) => {
          this.$message.error('项目数据获取失败')
        })
    },
    getTableList(data) {
      this.salaryList = data
      this.loading = false
      if (this.salaryList.length < 1) {
        this.isShow = true
      }
    },
    getSalaryState() {
      this.axios({
        method: 'post',
        url: 'api-su/cs/salary/expand/status',
      })
        .then((response) => {
          this.salaryStateOptions = response.data.result
        })
        .catch((error) => {
          this.$message.error('数据获取失败')
        })
    },
    downLoad(type) {
      this.axios({
        method: 'post',
        url: 'api-su/salary/expand/findurl',
        data: {
          name: type,
        },
      })
        .then(
          (response) => {
            if (!response.data.hasError) {
              window.open(response.data.result.url)
            } else {
              this.$message({
                type: 'error',
                message: response.data.msg,
              })
            }
          },
          (response) => {}
        )
        .catch((error) => {})
    },
    //跳转详情
    toSalaryDetail(index, row) {
      this.$router.push({
        path: '/home/salaryDf/salaryPayBatchDetailList',
        name: 'salaryPayBatchDetailList',
        query: {
          salaryId: row.id,
          yearQuery: row.year,
          statusQuery: row.status,
          batchNoInfo:
            row.year + '年' + row.month + '月第' + row.batchNo + '批次工资',
          projectId: this.projectId,
        },
      })
      this.$store.commit('CHANGE_SLIDER_NAME', {
        oldUrl: '/home/salaryDf/companySalaryBatchList',
        newUrl: this.$router.currentRoute.fullPath,
      })
    },
    handleEdit(index, row) {
      this.$router.push({
        path: '/home/constructSalary/editConstructSalary',
        name: 'editConstructSalary',
        query: {
          salaryId: row.id,
          month: row.month,
          year: row.year,
          projectId: row.projectId,
          projectName: row.projectName,
          type: 'list',
        },
      })

      this.$store.commit('CHANGE_SLIDER_NAME', {
        oldUrl: '/home/salaryDf/companySalaryBatchList',
        newUrl: this.$router.currentRoute.fullPath,
      })
    },
    // 搜索
    searchList() {
      if (this.date) {
        this.filterField.createTimeStart = this.date[0]
        this.filterField.createTimeEnd = this.date[1]
      } else {
        this.filterField.createTimeStart = ''
        this.filterField.createTimeEnd = ''
      }
      this.$refs.pagination.getTableListData()
    },
    toUploadFile(index, row) {
      this.salaryId = row.id
      this.uploadImg = []
      this.saveImgArr = []
      this.srcList = []
      this.oldSrcList = []
      this.getUploadSearchImg(this.salaryId)
      this.uploadContract = true
    },
    // 获取附件查询图片
    getUploadSearchImg(salaryId) {
      var data = {
        associatedName: 'T_CS_SALARY',
        associatedId: salaryId,
      }
      this.axios({
        method: 'post',
        url: 'api-f/files/list',
        data: data,
      })
        .then((response) => {
          // this.bankData = response.data;
          if (!response.data.hasError) {
            this.uploadImg = response.data.result
            for (var i = 0; i < this.uploadImg.length; i++) {
              this.saveImgArr.push({
                originalName: this.uploadImg[i].originalName,
                relativePath: this.uploadImg[i].relativePath,
                fileSize: this.uploadImg[i].fileSize,
                fileType: this.uploadImg[i].fileType,
              })
              this.srcList.push(this.uploadImg[i].absolutePath)
              this.oldSrcList.push(this.uploadImg[i].absolutePath)
            }
          } else {
            this.$message({
              type: 'error',
              message: '数据获取失败',
            })
          }
        })
        .catch((error) => {})
    },
    /**
     * @description: 改变图片地址
     */
    changeSrcList(val) {
      this.srcList = val
    },
    cancelUpload() {
      this.uploadContract = false
    },
    //保存附件
    saveUpload() {
      this.canLogin = true
      var data = {
        files: this.packageParams(this.saveImgArr),
        salaryId: this.salaryId,
      }
      this.axios({
        method: 'post',
        url: 'api-su/cs/salary/expand/upfile',
        data: data,
      })
        .then((response) => {
          this.canLogin = false
          if (!response.data.hasError) {
            this.$message({
              type: 'success',
              message: response.data.result,
            })
            this.uploadContract = false
            this.$refs.pagination.getTableListData() //列表中的按钮只加载列表
          } else {
            this.$message({
              type: 'error',
              message: '保存失败',
            })
          }
        })
        .catch((error) => {
          this.canLogin = false
        })
    },
    //导出工资表
    exporTableAjax(index, row) {
      var id = row.id
      var year = row.year
      window.location.href =
        common.commonApi +
        'api-su/cs/salary/expand/export?salaryId=' +
        id +
        '&year=' +
        year +
        '&access_token=' +
        localStorage.getItem('access_token')
    },
    deleteSalary(index, row) {
      this.$confirm('确认删除该工资表吗?', '提示', {
        cancelButtonClass: 'btn-custom-cancel',
        type: 'warning',
      })
        .then(() => {
          this.toDel(row.id, row.year)
        })
        .catch(() => {
          // this.$message.error("删除失败");
        })
    },
    toDel(salaryId, year) {
      this.axios({
        method: 'post',
        url: 'api-su/cs/salary/expand/delete',
        data: {
          salaryId: salaryId,
          year: year,
        },
      })
        .then(
          (response) => {
            if (!response.data.hasError) {
              this.$message({
                message: '删除成功',
                type: 'success',
              })
              //删除成功刷新列表
              this.$refs.pagination.getTableListData()
            } else {
              this.$message({
                message: response.data.errorMsg,
                type: 'error',
              })
            }
          },
          (response) => {}
        )
        .catch((error) => {})
    },
    //跳转制作工资表
    toCreateSalary() {
      // this.$router.push("/home/constructSalary/createConstructSalaryWay");
      localStorage.removeItem('projectSalary')
      this.$router.push({
        path: '/home/constructSalary/createConstructSalaryWay',
        name: 'createConstructSalaryWay',
        query: {
          projectId: this.projectId,
          projectName: this.projectName,
        },
      })
      this.$store.commit('CHANGE_SLIDER_NAME', {
        oldUrl: '/home/salaryDf/companySalaryBatchList',
        newUrl: this.$router.currentRoute.fullPath,
      })
    },
    //立即支付
    toPay(index, row) {
      // salaryId=ff8080816ed46d48016ed4e779810000&month=6&year=2019&projectId=ff8080816ea586a2016ea6f293d4004a&projectName=NBA&type=create
      this.$router.push({
        path: '/home/constructSalary/constructPaySalary',
        name: 'constructPaySalary',
        query: {
          salaryId: row.id,
          month: row.month,
          year: row.year,
          projectId: row.projectId,
          projectName: row.projectName,
          type: 'list',
        },
      })
      this.$store.commit('CHANGE_SLIDER_NAME', {
        oldUrl: '/home/salaryDf/companySalaryBatchList',
        newUrl: this.$router.currentRoute.fullPath,
      })
    },
    toPaySalary(index, row) {
      this.axios({
        method: 'post',
        url: '/api-su/bank/pushdata',
        data: {
          salaryId: row.id,
        },
      })
        .then(
          (response) => {
            if (!response.data.hasError) {
              this.$message({
                message: '成功',
                type: 'success',
              })
              //删除成功刷新列表
              this.$refs.pagination.getTableListData()
            } else {
              this.$message({
                message: response.data.errorMsg,
                type: 'error',
              })
            }
          },
          (response) => {}
        )
        .catch((error) => {})
    },
  },
}
</script>

<style lang="less" scoped>
.reminder {
  color: #666;
  font-size: 14px;
  background: #fffbe6;
  line-height: 36px;
  border-radius: 3px;
  padding: 0 24px;
  margin: 24px 24px 0 24px;
  i {
    color: #ffaa00;
    margin-right: 4px;
    font-size: 20px;
    vertical-align: -2px;
  }
}
.topSection {
  height: 67px;
  padding: 16px 24px 0 10px;
  background: #e4ebf1;
  border-radius: 4px 4px 0 0;
  margin: 0 24px 0px 24px;
  .topBox {
    .alignRight {
      text-align: right;
    }
    .createSalaryBut {
      background: #009588;
      border: 1px solid #009588;
      padding: 10px 23px;
      margin-left: 12px;
      &:hover {
        opacity: 0.8;
      }
    }
    .salaryAccountBut {
      color: #009588;
      border: 1px solid #009588;
      padding: 10px 23px;
      &:hover {
        background: rgba(0, 149, 136, 0.1);
      }
    }
    .projectState {
      display: inline-block;
      width: 60px;
      height: 20px;
      line-height: 20px;
      font-size: 12px;
      color: #fff;
      text-align: center;
      margin-left: 10px;
      font-weight: normal;
      margin-top: 5px;
    }
    /deep/.el-input__inner {
      font: bold 24px Microsoft YaHei;
      color: #333333;
      border: none;
      height: 30px;
      background: #e4ebf1;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
    /deep/.el-select__caret {
      color: #333;
      font-size: 20px;
      line-height: 30px;
    }
  }
  /deep/.tabs {
    margin-top: 21px;
  }
  /deep/.is-active {
    background: #fff;
  }
}
.topContent {
  background: #e4ebf1;
  height: 83px;
  line-height: 56px;
  padding: 15px 24px;
  margin: 24px;
  .titleTop {
    font: bold 18px Microsoft YaHei;
    color: #333333;
  }
}
.toDownload {
  font-size: 14px;
  color: #0098ce;
  cursor: pointer;
  &:hover {
    color: #0070f5;
    border-bottom: 1px solid #0070f5;
  }
}

.uploadBtn {
  line-height: 20px;
}

.mainCon {
  top: 233px;
}
.uploadBox {
  position: relative;
  .upLoadDom {
    position: absolute;
    top: 0;
    left: 0;
    opacity: 0;
    input {
      // font-size: 0;
      width: 136px;
      height: 36px;
      cursor: pointer;
    }
  }
}
.imgStyle {
  margin-top: 20px;
  li {
    position: relative;
    margin-right: 20px;
    margin-top: 10px;
    i {
      position: absolute;
      right: -6px;
      top: -10px;
      font-size: 20px;
    }
  }
}
@media screen and (min-width: 1280px) and (max-width: 1366px) {
  .searchInputWidth /deep/.el-form-item__label {
    width: 90px;
  }
}
@import '../../../static/css/filterArea.less';
</style>
